package com.huilan.hgt.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.huilan.hgt.entity.Email;
import com.huilan.hgt.entity.EmailAttachment;
import com.huilan.hgt.mapper.EmailAttachmentMapper;
import com.huilan.hgt.mapper.EmailMapper;
import com.huilan.hgt.service.EmailService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huilan.hgt.util.Constants;
import com.huilan.hgt.util.EmailUtils;
import com.huilan.hgt.util.PageUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.List;

/**
 * <p>
 * 邮件表 服务实现类
 * </p>
 *
 * @author ghy
 * @since 2018-11-02
 */
@Service
public class EmailServiceImpl extends ServiceImpl<EmailMapper, Email> implements EmailService {

    @Autowired
    private EmailMapper emailMapper;

    @Autowired
    private EmailAttachmentMapper emailAttachmentMapper;
    /**
     * 查询邮件发送历史
     *
     * @return
     * @param page
     */
    @Override
    public IPage<Email> selectEmailHistory(PageUtil<Email> page) {

        QueryWrapper<Email> queryWrapper = new QueryWrapper<>();

        if(Constants.isAdmin()){
            return emailMapper.selectEmailList(page);
        }else {
            //普通用户查询自己的邮件发送历史
            queryWrapper.eq(Email.CREATER,Constants.getCurrentUser().getUserId());
            return emailMapper.selectPage(page,queryWrapper);
        }
    }

    /**
     * 发送邮件
     * @param email
     * @param code
     * @param contextPath
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean sendMail(Email email, String code, String contextPath) {

        boolean isSend = false;
        String content = email.getEmailContent();
        if(StringUtils.isNotEmpty(code)){
            //服务器地址

            //将key进行URL编码
//                String encodeKey = URLEncoder.encode(key,"GBK");
            //拼接附件下载地址
            String downUrl = contextPath+"/attachment/download/"+code;

            //附件正文内容
            content = content+"<br/>附件下载地址：<a href="+downUrl+">"+downUrl+"</a>";

            email.setEmailContent(content);
        }
        String[] emails = email.getEmailAddress().split(",");

        isSend = EmailUtils.sendEmail(email.getEmailSubject(),emails,null,content,null);

        emailMapper.insert(email);

        EmailAttachment emailAttachment = new EmailAttachment();
        emailAttachment.setAttachmentCode(code)
                .setEmailId(email.getEmailId());

        emailAttachmentMapper.insert(emailAttachment);
        return isSend;
    }
}
